﻿namespace AppLab.Web
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Data.Objects.DataClasses;
    using System.IO;
    using System.Linq;
    using System.Web.Security;
    using AppLab.Data.Models;
    using AppLab.Web.Resources;
    using Wicresoft.AppFlow.Flows;
    using AppLab.Core;

    public partial class TaskSubmitData : FormData
    {
        #region 表单升级包

        [Display(AutoGenerateField = false)]
        public bool UpgradePackageEnable { get; set; }

        /// <summary>
        /// 升级包
        /// </summary>
        string submitUpgradePackage;
        [Display(Order = 5, Name = "ReviewCustomDataFormSubmitUpgradePackageLable", ResourceType = typeof(RegistrationDataResources))]
        public string SubmitUpgradePackage { get { return submitUpgradePackage; } set { submitUpgradePackage = value; } }

        #endregion

        [Display(AutoGenerateField = false)]
        public FlowState TestResultID { get; set; }

        [Display(AutoGenerateField = false)]
        public DateTime StartTime { get; set; }

        [Display(AutoGenerateField = false)]
        public DateTime TestTaskEAT { get; set; }

        [Display(AutoGenerateField = false)]
        public string TestReportName { get; set; }

        [Display(AutoGenerateField = false)]
        public byte[] TestReport { get; set; }

        [Display(AutoGenerateField = false)]
        public int TestTypeID { get; set; }

        [Display(AutoGenerateField = false)]
        public int Priority { get; set; }

        [Display(AutoGenerateField = false)]
        public string AssignedToAlias { get; set; }

        public Guid ToDataBase()
        {
            try
            {
                using (var dc = PMSEntities.Create())
                {
                    var flow = dc.tysx_AppFlow.First(p => p.FlowID == this.FlowGuid);
                    //添加tysx_TestTask表中元素
                    var tysx_TestTask = dc.tysx_TestTask.First(p => p.TestTaskID == flow.tysx_Submit.tysx_Review.TestTaskID);
                    {
                        tysx_TestTask.TestTypeID = TestTypeID;
                        tysx_TestTask.EndDate = DateTime.Now;
                        tysx_TestTask.TestResultID = (int)TestResultID;
                        tysx_TestTask.TestReportName = TestReportName;
                        tysx_TestTask.TestReport = TestReport;
                        flow.StateID = tysx_TestTask.TestResultID;
                        dc.SaveChanges();
                    }
                } 
                return this.FlowGuid;
            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("{0}({1}): Tasked is failed....", this.MoblieBrandAndType, this.MobileVersion));
                Log.WriteError(ex.Message);
                Log.WriteError(ex.StackTrace);
                return Guid.Empty;
            }
        }

        //public EntityObject ToDataBaseFormat()
        //{
        //    return new tysx_TestTask()
        //    {
        //        TestTypeID = TestTypeID,
        //        EndDate = DateTime.Now,
        //        TestResultID = (int)TestResultID,
        //        TestReportName = TestReportName,
        //        TestReport = TestReport,
        //    };
        //}

        #region 发送验收Email

        public void SendEmail()
        {
            string toList = "";
            string cCList = "";

            using (var dc = PMSEntities.Create())
            {
                if (this.TestResultID == FlowState.TestFailed)
                {
                    toList = dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == this.SubmitByAlias).Email;
                    cCList = dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == this.AssignedToAlias).Email;
                }
                else
                {
                    string[] aliasList = Roles.GetUsersInRole("Publish");
                    foreach (string alias in aliasList)
                    {
                        toList += dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == alias).Email + ";";
                    }

                    cCList = dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == this.AssignedToAlias).Email;
                    cCList += ";" + dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == this.SubmitByAlias).Email;
                }
            }

            if (string.IsNullOrEmpty(toList)) return;

            if (this.TestResultID == FlowState.TestFailed)
            {
                //验收不通过，告知提交者，抄送给验收者
                string subject = "新的适配验收未通过！";
                string bodyStr = System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\TestedPackage.htm"));
                bodyStr = string.Format(bodyStr, this.SubmitBy, "验收未通过", this.MobileBrand, this.MobileType, this.MobileVersion,
                    this.SubmitBy, this.SubmitTime.ToString("yyyy-MM-dd HH:mm"), this.ReviewBy, this.ReviewTime.ToString("yyyy-MM-dd HH:mm"),
                    this.AssignedTo, DateTime.Now.ToString("yyyy-MM-dd HH:mm"), "验收未通过");
                MailUtility.SendMail(toList, cCList, subject, bodyStr);
            }
            else
            {
                //验收通过，告知发布者，抄送给验收者和提交者
                string subject = "新的适配已验收完毕！";
                string bodyStr = System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\TestedPackage.htm"));
                bodyStr = string.Format(bodyStr, "all", "已验收完毕", this.MobileBrand, this.MobileType, this.MobileVersion,
                    this.SubmitBy, this.SubmitTime.ToString("yyyy-MM-dd HH:mm"), this.ReviewBy, this.ReviewTime.ToString("yyyy-MM-dd HH:mm"),
                    this.AssignedTo, DateTime.Now.ToString("yyyy-MM-dd HH:mm"), TestResultID == FlowState.TestSucceeded ? "验收通过" : "验收保留意见");
                MailUtility.SendMail(toList, cCList, subject, bodyStr);
            }
        }
        #endregion
    }
}